package com.example.tellwin.question;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.tellwin.MainApplication;
import com.example.tellwin.PhotoActivity;
import com.example.tellwin.R;
import com.example.tellwin.base.CpBaseFragment;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.mine.act.OrderListActivity;
import com.example.tellwin.mine.bean.GradeBean;
import com.example.tellwin.mine.bean.SubjectBean;
import com.example.tellwin.question.adapter.PhotoAdapter;
import com.example.tellwin.question.adapter.VoiceAdapter;
import com.example.tellwin.question.bean.VoiceBean;
import com.example.tellwin.question.contract.QuestionContract;
import com.example.tellwin.question.presenter.QuestionPresenter;
import com.example.tellwin.utils.CommonUtils;
import com.example.tellwin.utils.ImageUtils;
import com.example.tellwin.utils.LogUtil;
import com.example.tellwin.utils.MediaUtils;
import com.example.tellwin.utils.ToastUtil;
import com.example.tellwin.view.SelectWheelDialog;
import com.example.tellwin.view.TakePhotoDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.example.tellwin.common.Common.VocieRequestCode;

/**
 *
 */
public class QuestionFragment extends CpBaseFragment implements QuestionContract.View {

    @BindView(R.id.class_tv)
    TextView classTv;
    @BindView(R.id.course_tv)
    TextView courseTv;
    @BindView(R.id.question_title_et)
    EditText questionTitleEt;
    @BindView(R.id.upload_pic_ll)
    LinearLayout uploadPicLl;
    @BindView(R.id.voice_describe_ll)
    LinearLayout voiceDescribeLl;
    @BindView(R.id.pic_rv)
    RecyclerView picRv;
    @BindView(R.id.voice_rv)
    RecyclerView voiceRv;
    @BindView(R.id.quesiton_commit_tv)
    TextView quesitonCommitTv;
    @BindView(R.id.content_et)
    EditText contentEt;

    private Unbinder unbinder;

    private TakePhotoDialog takePhotoDialog;

    private List<String> photoPaths = new ArrayList<>();
    private List<VoiceBean> voiceBeans = new ArrayList<>();
    private PhotoAdapter photoAdapter;
    private VoiceAdapter voiceAdapter;

    private List<String> photoUrl;
    private List<VoiceBean> voiceUrls;

    List<GradeBean> gradeList = new ArrayList<>();
    List<SubjectBean> subjectList = new ArrayList<>();
    private SelectWheelDialog gradeDialog;
    private SelectWheelDialog subjectDialog;

    private MediaPlayer mediaPlayer;

    @Inject
    QuestionPresenter mPresenter;

    public void onPhotoResult() {
        String photoPath = takePhotoDialog.getTakePhotoPath();
        photoPaths.add(photoPath);
        photoAdapter.notifyDataSetChanged();
    }

    public void addPhotoPath(String path) {
        photoPaths.add(path);
        photoAdapter.notifyDataSetChanged();
        setConfrimBtnEnable();
    }

    @Override
    public View onCreateRootView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_question, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(view);
        initData();
        initEvent();
        return view;
    }

    private void initView(View view) {

        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        picRv.setLayoutManager(gridLayoutManager);
        picRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int postion = parent.getChildAdapterPosition(view);
                if (postion >= 2) {
                    outRect.top = getResources().getDimensionPixelOffset(R.dimen.dp_15);
                }
                if (postion % 2 == 1) {
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.dp_7);
                } else {
                    outRect.right = getResources().getDimensionPixelOffset(R.dimen.dp_7);
                }
            }
        });
        photoAdapter = new PhotoAdapter();
        picRv.setAdapter(photoAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        voiceRv.setLayoutManager(linearLayoutManager);
        voiceRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int postion = parent.getChildAdapterPosition(view);
                if (postion > 0) {
                    outRect.top = getResources().getDimensionPixelOffset(R.dimen.dp_15);
                }
            }
        });
        voiceAdapter = new VoiceAdapter();
        voiceRv.setAdapter(voiceAdapter);
        mediaPlayer = new MediaPlayer();
    }

    private void initData() {
        photoAdapter.setPhotoPaths(photoPaths);
        voiceAdapter.setVoiceBeans(voiceBeans ,true);
        mPresenter.getGradeList();
        mPresenter.getSubjectList();
    }

    private void initEvent() {
        photoAdapter.setPhotoClickListener(new PhotoAdapter.PhotoClickListener() {
            @Override
            public void onDelteClick(int position) {
                photoPaths.remove(position);
                photoAdapter.notifyDataSetChanged();
            }

            @Override
            public void onItemClick(int position, String path) {
                Intent intent = new Intent(getActivity(), PhotoActivity.class);
                ArrayList<String> photoPaths = new ArrayList<>();
                photoPaths.add(path);
                intent.putExtra(Common.PHOTO_PATH, photoPaths);
                startActivity(intent);
            }
        });
        questionTitleEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setConfrimBtnEnable();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        contentEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setConfrimBtnEnable();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        voiceAdapter.setOnVoiceItemClick(new VoiceAdapter.OnVoiceItemClick() {
            @Override
            public void onVoiceItemClick(int postion, VoiceBean voiceBean) {
                try {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(voiceBean.getPath());//设置播放来源
                    mediaPlayer.prepareAsync();//异步准备
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        //异步准备监听
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            mediaPlayer.start();//播放
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onItemDeleteClick(int postion, VoiceBean voiceBean) {
                voiceBeans.remove(postion);
                voiceAdapter.notifyDataSetChanged();
            }
        });

    }

    @OnClick({R.id.class_tv, R.id.course_tv, R.id.upload_pic_ll, R.id.voice_describe_ll, R.id.quesiton_commit_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.class_tv:
                showGradeDailog();
                break;
            case R.id.course_tv:
                showSubjectDialog();
                break;
            case R.id.upload_pic_ll:
                uploadPic();
                break;
            case R.id.voice_describe_ll:
                startRecord();
                break;
            case R.id.quesiton_commit_tv:
                if (photoPaths != null && photoPaths.size() > 0) {
                    mPresenter.uploadPhoto(photoPaths);
                } else if (voiceBeans != null && voiceBeans.size() > 0) {
                    mPresenter.uploadVoice(voiceBeans);
                } else {
                    mPresenter.uploadQuestion(photoUrl, voiceUrls, (String) classTv.getTag(), (String) courseTv.getTag(), questionTitleEt.getText().toString(), contentEt.getText().toString());
                }
                // startActivity(AnswerActivity.class);
                break;
        }
    }

    private void showGradeDailog() {
        if (gradeDialog == null) {
            gradeDialog = new SelectWheelDialog(getActivity(), new ArrayList<>(gradeList));
            gradeDialog.setTitle(getResources().getString(R.string.select_grade));
            gradeDialog.setOnSelectListener((position, str) -> {
                GradeBean gradeBean = gradeList.get(position);
                classTv.setText(gradeBean.getGradeName());
                classTv.setTag(gradeBean.getGradeId());
                setConfrimBtnEnable();
            });
        }
        gradeDialog.show();
    }

    private void showSubjectDialog() {
        if (subjectDialog == null) {
            subjectDialog = new SelectWheelDialog(getActivity(), new ArrayList<>(subjectList));
            subjectDialog.setTitle(getResources().getString(R.string.select_subjects_title));
            subjectDialog.setOnSelectListener((position, str) -> {
                SubjectBean subjectBean = subjectList.get(position);
                courseTv.setText(subjectBean.getSubjectName());
                courseTv.setTag(subjectBean.getSubjectId());
                setConfrimBtnEnable();
            });
        }
        subjectDialog.show();
    }

    private void setConfrimBtnEnable() {
        if (classTv.getTag() == null) {
            quesitonCommitTv.setEnabled(false);
            return;
        }
        if (courseTv.getTag() == null) {
            quesitonCommitTv.setEnabled(false);
            return;
        }
        if (TextUtils.isEmpty(questionTitleEt.getText().toString())) {
            quesitonCommitTv.setEnabled(false);
            return;
        }
        if (TextUtils.isEmpty(contentEt.getText().toString())) {
            quesitonCommitTv.setEnabled(false);
            return;
        }
        quesitonCommitTv.setEnabled(true);
    }

    private void uploadPic() {
        if (takePhotoDialog == null) {
            takePhotoDialog = new TakePhotoDialog(getActivity());
        }
        takePhotoDialog.show();
    }

    /**
     * 启动录音机，创建文件
     */
    public void startRecord() {
        if (!CommonUtils.requestPermissions(getActivity())) {
            return;
        }
        Intent intentRecord = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intentRecord.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intentRecord.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        startActivityForResult(intentRecord, VocieRequestCode);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case VocieRequestCode:
                    Uri uri = data.getData();
                    if (uri != null) {
                        String path = ImageUtils.uriToRealPath(getActivity(), uri);
                        LogUtil.e(path);
                        VoiceBean voiceBean = new VoiceBean();
                        voiceBean.setPath(path);
                        voiceBean.setUri(uri);
                        voiceBean.setTime(MediaUtils.getMediaTime(getContext(), uri));
                        voiceBeans.add(voiceBean);
                        voiceAdapter.notifyDataSetChanged();
                        setConfrimBtnEnable();
                    }
                    break;
            }
        }
    }

    private void uploadQuestion() {
        mPresenter.uploadQuestion(photoUrl, voiceUrls, (String) classTv.getTag(), (String) courseTv.getTag(), questionTitleEt.getText().toString(), contentEt.getText().toString());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void gradeListResult(List<GradeBean> gradeBeans) {
        this.gradeList = gradeBeans;
        if (gradeDialog != null) {
            gradeDialog.setMiddleList(new ArrayList<>(gradeList));
        }
    }

    @Override
    public void subjectListResult(List<SubjectBean> subjectBeans) {
        this.subjectList = subjectBeans;
        if (subjectDialog != null) {
            subjectDialog.setMiddleList(new ArrayList<>(subjectList));
        }
    }

    @Override
    public void uploadPhotoResult(List<String> photoUrls) {
        this.photoUrl = photoUrls;
        if (voiceBeans != null && voiceBeans.size() > 0) {
            mPresenter.uploadVoice(voiceBeans);
        } else {
            uploadQuestion();
        }
    }

    @Override
    public void uploadVocieResult(List<VoiceBean> voiceUrls) {
        this.voiceUrls = voiceUrls;
        uploadQuestion();
    }

    @Override
    public void uploadQuestionSuccess() {
        classTv.setText("");
        classTv.setTag(null);
        contentEt.setText("");
        courseTv.setText("");
        courseTv.setTag(null);
        questionTitleEt.setText("");
        photoPaths.clear();
        voiceBeans.clear();
        photoAdapter.notifyDataSetChanged();
        voiceAdapter.notifyDataSetChanged();
        setConfrimBtnEnable();
        Intent intent = new Intent(getContext(), OrderListActivity.class);
        startActivity(intent);
    }
}
